﻿namespace PowerSong.UserInterface
    {
    using System;
    using System.IO;
    using System.Net;
    using System.Windows;
    using PowerSong.Export;
    using PowerSong.SongDatabase;
    using PowerSong.UserInterface.Tasks;

    /// <summary>
    /// Interaction logic for ExportWindow.xaml
    /// </summary>
    public partial class ExportWindow : Window
        {

        public ExportWindow()
            {
            InitializeComponent();
            ExportToOpenLyricsRadioButton.IsChecked = true;
            }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
            {
            this.DialogResult = false;
            }

        private void OKButton_Click(object sender, RoutedEventArgs e)
            {

            // Collate styles so that the user can select them, but only if they choose an option that allows it
            var styles = SubmitSongsToWebsiteRadioButton.IsChecked == true
                ? State.Database.Styles.GetAllStyles()
                : new PowerSong.SongDatabase.Style[] { };

            // Ask the user what they wish to export
            var window = new SelectItemsWindow(State.Database.Songs.GetAllSongs(), styles);
            if (window.ShowDialog() == true)
                {

                // Ensure at least one item has been selected
                if (window.SelectedStyles.Length == 0 && window.SelectedSongs.Length == 0)
                    {
                    Utilities.ShowErrorMessage("Please select at least one item to export.");
                    return;
                    }

                // Perform the export
                string[] result = null;
                if (ExportToOpenLyricsRadioButton.IsChecked == true)
                    {
                    var location = SelectFolderControl.RequestFolderName("Please select an empty folder in which to place the OpenLyrics database.");
                    if (location != null)
                        {
                        result = ExportToOpenLyrics(location, window.SelectedSongs);
                        }
                    }
                else if (ExportToPresenterRadioButton.IsChecked == true)
                    {
                    var location = SelectFolderControl.RequestFolderName("Please select an empty folder in which to place the Presenter database.");
                    if (location != null)
                        {
                        result = ExportToPresenter(location, window.SelectedSongs);
                        }
                    }
                else if (SubmitSongsToWebsiteRadioButton.IsChecked == true)
                    {
                    result = ExportToWebsite(window.SelectedSongs, window.SelectedStyles);
                    }

                // Was the export successful?
                if (result != null)
                    {

                    // Show messages
                    if (result.Length > 0) MessagesWindow.Show("The following problems occurred during the export. Please review these messages before continuing.", result);

                    // All done!
                    Utilities.ShowInformationMessage("Completed", "The data has been exported.");
                    this.DialogResult = true;

                    }

                }

            }

        private string[] ExportToOpenLyrics(string location, Song[] songs)
            {

            // Ensure the target location does not contain any files
            if (Directory.GetFiles(location).Length > 0 || Directory.GetDirectories(location).Length > 0)
                {
                Utilities.ShowErrorMessage("Error", "The folder '" + location + "' is not empty. Please specify a location for the new OpenLyrics database that does not contain any folders or files.");
                return null;
                }

            // Go ahead and actually export the data
            var exporter = new OpenLyricsExport(State.Database, songs, location);
            var task = new ExportTask(exporter, "Exporting items from the PowerSong database into the OpenLyrics database...");
            ProgressWindow.Start(task);
            return task.Messages;

            }

        private string[] ExportToPresenter(string location, Song[] songs)
            {

            // Ensure the target location does not contain any files
            if (Directory.GetFiles(location).Length > 0 || Directory.GetDirectories(location).Length > 0)
                {
                Utilities.ShowErrorMessage("Error", "The folder '" + location + "' is not empty. Please specify a location for the new Presenter database that does not contain any folders or files.");
                return null;
                }

            return new string[] { };

            }

        private string[] ExportToWebsite(Song[] songs, PowerSong.SongDatabase.Style[] styles)
            {

            // Save a new database to a temporary file
            var fileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".PowerSong");
            try
                {
                var newDatabase = Database.Create(fileName);

                // Add items to the temporary database            
                foreach (var style in styles) newDatabase.Styles.Write(style);
                foreach (var song in songs) newDatabase.Songs.Write(song);
                newDatabase.Compact();

                // Submit the database file to the PowerSong website for consideration
                var client = new WebClient();
                client.UploadFile(Infrastructure.SubmitUrl, fileName);

                // All done!
                Utilities.ShowInformationMessage("Submission Successful", "Thanks for your submission! Your data has been successfully submitted to the PowerSong website.", "It will be reviewed prior to being made available for others to download in the near future.");
                return new string[] { };

                }
            catch (Exception ex)
                {
                Utilities.ShowErrorMessage("Error", "An error has occurred:", ex.Message);
                return null;
                }
            finally
                {

                // Ensure the temporary file is always deleted
                if (File.Exists(fileName)) File.Delete(fileName);

                }

            }

        }

    }
